﻿using System.Collections.Generic;
using System.Data;

public class ExcelReader
{
    /// <summary> 配置表字符串内容 </summary>
    private DataTable _excelData = null;

    /// <summary> 属性名 </summary>
    private Dictionary<string, int> _columnNames;

    public ExcelReader(DataTable excelData)
    {
        _excelData = excelData;
        SetColumnNames();
    }

    /// <summary> 设置属性名 </summary>
    void SetColumnNames()
    {
        _columnNames = new Dictionary<string, int>();
        int columns = _excelData.Columns.Count;

        for (int i = 0; i < columns; i++)
        {
            string fieldName = _excelData.Rows[3][i].ToString();
            _columnNames[fieldName] = i;
            UnityEngine.Debug.Log(fieldName +"---"+ i);
        }
    }

    /// <summary> 行 </summary>
    public int GetRowCount()
    {
        if (null == _excelData) return 0;

        return _excelData.Rows.Count;
    }

    /// <summary> 列 </summary>
    int GetColumnCount()
    {
        if (null == _excelData) return 0;

        return _excelData.Columns.Count;
    }

    /// <summary>
    /// 通过属性名获取到列下标
    /// </summary>
    int GetColumnIndex(string columnName)
    {
        if (string.IsNullOrEmpty(columnName))
        {
            return -1;
        }

        int columnIndex = -1;
        _columnNames.TryGetValue(columnName, out columnIndex);
        return columnIndex;
    }

    /// <summary>
    /// 获取数据
    /// </summary>
    public string GetData(int row, string columnName)
    {
        if (row < 0 || row >= GetRowCount()) { return null; }
        int columnIndex = GetColumnIndex(columnName);
        if (columnIndex < 0 || columnIndex >= GetColumnCount()) { return null; }

        return _excelData.Rows[row][columnIndex].ToString();
    }
}
